package cn.aaa.template;

import cn.aaa.config.TxMapProperties;
import cn.aaa.domain.DistanceResult;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TxMapTemplate {
    public static final String DRIVING = "driving";
    private TxMapProperties properties;

    public TxMapTemplate(TxMapProperties properties) {
        this.properties = properties;
    }

    public DistanceResult distanceMeasure(String mode, double fromLat, double fromLng
            , double toLat , double toLng) {
        //拼接测距请求
        String url = String.format(properties.getDistanceUrl(),
                mode,fromLat, fromLng, toLat, toLng, properties.getKey());

        HttpResponse execute = HttpRequest.get(url).execute();
        String body = execute.body();
        JSONObject jsonObject = JSON.parseObject(body);
        //判断结果
        if(!jsonObject.get("status").toString().equals("0")){
            throw new RuntimeException(jsonObject.get("message").toString());
        }

        //拿到结果
        JSONObject result = jsonObject.getJSONObject("result");
        //rows是数组
        JSONArray rows = result.getJSONArray("rows");
        if(rows.size() == 0)throw new RuntimeException("没有测距结果");

        JSONArray elements = rows.getJSONObject(0).getJSONArray("elements");
        if(elements.size() == 0)throw new RuntimeException("没有测距结果");

        DistanceResult distanceResult = elements.getObject(0, DistanceResult.class);
        return distanceResult.of();
    }

}
